package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;

/**
 * 日志数据分流
 *
 * 启动日志---启动侧输出流
 * 曝光日志---曝光侧输出流
 * 页面日志---主流
 */


public class BaseLogApp {
    public static void main(String[] args) throws Exception {
        // 1  基本环境准备
        //1.1 设置流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);


//        // 2  检查点相关的设置
//        //2.1 开启检查点
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        //2.2 设置检查点超时时间
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        //2.3 job取消之后，检查点是否保留
//        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
//        //2.4 两个检查点之间最小间隔
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
//        //2.5 设置重启策略
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
//        //2。6 设置状态后端
//        env.setStateBackend(new FsStateBackend("hdfs://hadoop102:8020/gmall/ck"));
//        //2.7 设置操作hadoop的用户
//        System.setProperty("HADOOP_USER_NAME","wjh");



        // 3  从kafka的ods_base_log读取数据
        String topic = "ods_base_log";
        String groupId = "base_log_app_group";
        //获取消费者对象
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //消费数据封装为流
        DataStreamSource<String> kafkaStrDs = env.addSource(kafkaSource);


        // 4  对流中数据类型进行转换    jsonStr -> jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDs.map(
                new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String s) throws Exception {
                        return JSON.parseObject(s);
                    }
                }
        );

        // 5  使用flink状态编程，修复新老访客标记
        // 按照mid将相同的设备放到一组
        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(
                jsonObj -> jsonObj.getJSONObject("common").getString("mid")
        );
        //修复
        SingleOutputStreamOperator<JSONObject> jsonObjWithIsNewDS = keyedDS.map(
                new RichMapFunction<JSONObject, JSONObject>() {
                    private ValueState<String> lastVisitDateState;
                    private SimpleDateFormat sdf;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVisitDateState", String.class));
                        sdf = new SimpleDateFormat("yyyyMMdd");
                    }

                    @Override
                    public JSONObject map(JSONObject jsonObject) throws Exception {
                        //获取新老访客标记
                        String isNew = jsonObject.getJSONObject("common").getString("is_new");
                        Long ts = jsonObject.getLong("ts");
                        String curVisitDate = sdf.format(ts);

                        if ("1".equals(isNew)) {
                            //从状态中获取曾经访问日期
                            String lastvisitDate = lastVisitDateState.value();
                            if (lastvisitDate != null && lastvisitDate.length() > 0) {
                                //访问过，修复标记
                                if (!lastvisitDate.equals(curVisitDate)) {
                                    isNew = "0";
                                    jsonObject.getJSONObject("common").put("is_new", isNew);
                                }
                            } else {
                                //没有访问过   这是第一次访问  将这次访问日期放到状态中保存
                                lastVisitDateState.update(curVisitDate);
                            }
                        }
                        return jsonObject;

                    }
                }
        );
        jsonObjWithIsNewDS.print(">>>");


        // 6  使用flink侧输出流完成分流
        OutputTag<String> startTag = new OutputTag<String>("startTag"){};
        OutputTag<String> displayTag = new OutputTag<String>("displayTag"){};

        SingleOutputStreamOperator<String> pageDS = jsonObjWithIsNewDS.process(
                new ProcessFunction<JSONObject, String>() {
                    @Override
                    public void processElement(JSONObject jsonObj, Context ctx, Collector<String> out) throws Exception {
                        JSONObject startJsonObj = jsonObj.getJSONObject("start");
                        if (startJsonObj != null && startJsonObj.size() > 0) {
                            ctx.output(startTag, jsonObj.toJSONString());
                        } else {
                            out.collect(jsonObj.toJSONString());
                            JSONArray displayArr = jsonObj.getJSONArray("displays");
                            if (displayArr != null && displayArr.size() > 0) {
                                String pageId = jsonObj.getJSONObject("page").getString("page_id");
                                Long ts = jsonObj.getLong("ts");
                                for (int i = 0; i < displayArr.size(); i++) {
                                    JSONObject displayJsonObj = displayArr.getJSONObject(i);
                                    displayJsonObj.put("page_id", pageId);
                                    displayJsonObj.put("ts", ts);
                                    ctx.output(displayTag, displayJsonObj.toJSONString());
                                }
                            }
                        }
                    }
                }
        );
        DataStream<String> startDS = pageDS.getSideOutput(startTag);
        DataStream<String> displayDS = pageDS.getSideOutput(displayTag);

        pageDS.print("---");
        startDS.print("+++");
        displayDS.print("$$$");


        // 7  将不同流的数据写到kafka的不同主题中
        pageDS.addSink(MyKafkaUtil.getKafkaSink("dwd_page_log"));
        startDS.addSink(MyKafkaUtil.getKafkaSink("dwd_start_log"));
        displayDS.addSink(MyKafkaUtil.getKafkaSink("dwd_display_log"));


        env.execute();

    }
}


